* Replication File "Asymmetric Crime Dynamics In and Out of Lockdowns"
* Author: Ruben Poblete-Cazenave
* Date: February 9, 2024.

clear all
set more off
program drop _all
macro drop _all
capture log close
 
use  "database_crime_covid.dta", clear	

global crime_list_adj = "theft_adj burglary_adj robbery_adj murder_adj kidnapping_adj women_crime_adj riot_adj" 
global crime_list_demeaned_adj = "theft_demeaned_adj robbery_demeaned_adj burglary_demeaned_adj murder_demeaned_adj kidnapping_demeaned_adj women_crime_demeaned_adj riot_demeaned_adj"

global esttab_opts "b(%9.3f) se sfmt(%9.3f) starlevels(* 0.10 ** 0.05 *** 0.01) nogaps staraux r2"
global block_controls "share_urban share_male share_literacy share_SCST share_work"	 


*-------------------------------------------------------------------------------
* FIGURE 1 
*-------------------------------------------------------------------------------
quietly: sum date
global min_date = r(min)
global max_date = r(max) 
tab date if date == $max_date
	

preserve
local var_list `" "num_cases_adj" "num_cases_demeaned_adj"  "'
foreach crime of local var_list {
	display "`crime'"

	* Get the mean of crime for each date
	bysort rdcontinuous: egen dailymean_`crime' = mean(`crime')
}
	capture bysort rdcontinuous: egen dailymean_gmi = mean(gmi)
	sort ps_code date
	capture gen moveave_3days_gmi = (F.dailymean_gmi + dailymean_gmi + L.dailymean_gmi)/3
	
	collapse dailymean_* num_cases_demeaned date Zones year stringency  moveave_3days_gmi, by(rdcontinuous) fast
	rename rdcontinuous running_day


gen stringency2 = stringency - 100
local date_lockdown = 21996
local date_lockdown_ease = 22025
local date_no_lockdown = 22067
local day_ease = `date_lockdown_ease' - `date_lockdown'	
local crime = "num_cases_adj"
local cutter = 30
local dates_graph "21915 `date_lockdown' `date_lockdown_ease' 22039 22053 `date_no_lockdown'  22097 22105 22112 22128"

	twoway  scatter dailymean_`crime' date , mcolor(black) msize(vsmall) msymbol(O) mfcolor(none)	/*
		*/xline(`dates_graph', lpattern(longdash) lcolor(gs12) lwidth(vthin)) /*	
		*/|| line stringency2 date if year >= 2020 & date < $max_date, yaxis(2) lcolor(brown) lpattern(dash)/*
		*/|| line moveave_3days_gmi date if year >= 2020 & date < $max_date, yaxis(2) lcolor(gray) /*
			*/graphregion(fcolor(white) lcolor(white)) /*
			*/ legend(label (1 "Crime") label (2 "Stringency Index") label (3 "Mobility index") col(3) size(small) pos(6)) /*
			*/ytitle("Number of Crimes") /*
			*/ytitle("Stringency Index/ Mobility Index",axis(2)) /*
			*/xtitle(" ")				/*
			*/ylabel(,labsize(small)  axis(1))/*
			*/ylabel(,labsize(small)  axis(2))/*
			*/xlabel(`dates_graph',labsize(small) angle(45)) 
			graph export "tables and figures\daily_crimes.pdf", replace
			
restore

*------------------------------------------------------------------------------*
* Figure 2
*------------------------------------------------------------------------------*
local cutter = 6*7    
local llband = (28) 

pause off
foreach crime in num_cases_demeaned_adj $crime_list_demeaned_adj {
preserve

display "-------"
display "`crime'"
display "-------"
	
tempfile local_linear_run
save `local_linear_run'

	* Get the mean of crime for each date 
	collapse `crime', by(rdcontinuous) fast
	rename rdcontinuous running_day
	tempfile means
	save `means'

postutil clear
tempname locallinear
			
postfile `locallinear' running_day predicted_rob upperCI lowerCI using "local_linear_graphs_day.dta", replace

	forvalues day =  -`cutter'/`cutter'{   
			use `local_linear_run', clear
			
			quietly {
				keep if rdcontinuous >= `day' - `llband' & rdcontinuous <= `day' + `llband' 
				count 
				display `day'
				
				* RD Estimation with linear trend
				reg `crime' lockdown running_day lockdown_day 
			
				* Set values for the variables in the regression in order to make the prediction.
				clear
				set obs 1
				gen lockdown = (`day' >= 0)
				gen running_day =  `day' * (1 - lockdown)
				gen lockdown_day = `day' * lockdown
			
				** predict estimates based on estimated betas and values of the variables above.
				predict localestimate
				** predict standard error of estimate;
				predict reg_st_dev, stdp
				** Make CI around estimate;
				gen upperCI = localestimate + 1.96 * reg_st_dev
				gen lowerCI = localestimate - 1.96 * reg_st_dev
				
				sum localestimate reg_st_dev upperCI lowerCI
			
			}
			
			post `locallinear' (`day') (localestimate) (upperCI) (lowerCI) 
		
	}
	
	postclose `locallinear'

	use "local_linear_graphs_day.dta", clear
	append using `means'
	
	drop if running_day < -`cutter' | running_day > `cutter'

*#delimit;
	twoway line predicted_rob running_day if running_day < 0, lcolor(black) /*
		*/|| line predicted_rob running_day if running_day >= 0, lcolor(black) /*	
		*/xline(0 /*28*/, lpattern(longdash) lcolor(gray)) /*
		*/|| scatter `crime' running_day, mcolor(gs12) msize(small) msymbol(O) mfcolor(none)	/*
			*/graphregion(fcolor(white) lcolor(white)) /*
			*/legend(off) /*
			*title(`crime') 				
			*ylabel(-.15(.05).1)
			*/ytitle("Daily crimes per police station") /*
			*/xtitle("Day")	/*
			*/xlabel(-`cutter'(7)`cutter') /*
			*/ 
			* saving("figures/local_linear_`crime'", replace)
			*ytitle("Number of Crimes")

			
restore
more
pause Type "end" to continue
	graph export "tables and figures/local_linear_`crime'.pdf", replace
}			





*------------------------------------------------------------------------------*
* Table 3:
*------------------------------------------------------------------------------*
* Program to replace _se[lockdown] with two-way clustered std error Cameron, Gelbach, and Miller (2011).
global crime_list_est = "theft burglary robbery murder kidnapping women_crime riot"

capture program drop twoway_clustered_se
program twoway_clustered_se, eclass

	cls
	eststo clear	
	local cluster_group = "PS date ps_date" 
	local bandwidth =21

	foreach crime in num_cases  $crime_list_est {
		foreach cluster_dimension in `cluster_group' {

			quietly: reg `crime'_demeaned_adj lockdown rdcontinuous lockdown_rdcon i.dow temp rain if rdcontinuous >= -`bandwidth' & rdcontinuous <= `bandwidth'-1, cluster(`cluster_dimension') 
				local var_`cluster_dimension'_lockdown = _se[lockdown]^2		
				local var_`cluster_dimension'_day = _se[rdcontinuous]^2		
				local var_`cluster_dimension'_lockdown_rdcon= _se[lockdown_rdcon]^2	
			}
			
			* Dimesions for clustering:
			if "`cluster_group'" == "PS date ps_date"   {
				local cluster_vars_lockdown = 	 `var_PS_lockdown'  + `var_date_lockdown' - `var_ps_date_lockdown'
				local cluster_vars_day =     	 `var_PS_day' 		+ `var_date_day' 	  - `var_ps_date_day'
				local cluster_vars_lockdown_rdcon =`var_PS_lockdown_rdcon'  + `var_date_lockdown_rdcon' - `var_ps_date_lockdown_rdcon'
				}
			else if "`cluster_group'" == "id date id_date"   {
				local cluster_vars_lockdown = 	 `var_id_lockdown'  + `var_date_lockdown' - `var_id_date_lockdown'
				local cluster_vars_day =     	 `var_id_day' 		+ `var_date_day' 	  - `var_id_date_day'
				local cluster_vars_lockdown_rdcon =`var_id_lockdown_rdcon'  + `var_date_lockdown_rdcon' - `var_id_date_lockdown_rdcon'
			}

		* Replace _se[lockdown] with two-way clustered std error
		   tempvar esave		   
		   qui estsave, gen(`esave')
		   qui estsave, from(`esave')
		   tempname V 
		   matrix `V' = e(V)
		   matrix `V'[1,1] = `cluster_vars_lockdown'
		   matrix `V'[2,2] = `cluster_vars_day'
		   matrix `V'[3,3] = `cluster_vars_lockdown_rdcon'
		   ereturn repost V = `V'

			** Generate pre-lockdown mean (March 2020);
			quietly{
			sum `crime'_adj if rdcontinuous >= -`bandwidth' & rdcontinuous < 0 & year >= 2020 
			estadd scalar priordailymean = r(mean)
			estadd scalar shareofmean = _b[lockdown] / r(mean)	
			}
			display "`crime'"
		   _eststo `crime'	
	}
  end
  
twoway_clustered_se

	#delimit;
	estout, cells(b(/*star*/ fmt(3)) se(par fmt(3)) ) 
			keep (lockdown rdcontinuous lockdown_rdcon ) 
			stats(priordailymean shareofmean, fmt(%9.3f %9.3f) 
			labels("Average crime pre-lockdown" "Proportion"));

	#delimit;
	esttab using "tables and figures\main_clustered.tex", /* b(%9.3f) se(%9.3f) nostar */
		keep(lockdown rdcontinuous lockdown_rdcon)	/*label*/ nonotes  
		subs("Date x Lockdown" "Date $\times$ Lockdown ") label
		mtitle("All crimes" "Theft" "Burglary" "Robbery" "Murder" "Kidnapping" "\shortstack{Against\\Women}" "Rioting" )
		replace
		$esttab_opts
		stats(N priordailymean shareofmean, fmt(%9.0fc %9.3f %9.3f) label("Observations" "Pre-lockdown Mean" "Share of Mean"));


	
		
*------------------------------------------------------------------------------*
* Table 4
*------------------------------------------------------------------------------*

capture program drop twoway_clustered_se
program twoway_clustered_se, eclass

	cls
	eststo clear	
	local cluster_group = "PS date ps_date" 
	local bandwidth = 21
	local vars = `"  "above_ps_pop" "above_court" "po_pop" "mobility_gmi" "compliance"   "'
	local crime num_cases_demeaned_adj
	local crime_pre_mean num_cases_adj
		sum `crime' 
	
eststo clear
foreach variable in `vars' {
	
	foreach num of numlist 0/1 {
	
		foreach crime in num_cases_demeaned_adj {		
		display "`crime'"
		foreach cluster_dimension in `cluster_group' {
		
			quietly: reg  `crime' lockdown rdcontinuous lockdown_rdcon i.dow rain temp if rdcontinuous >= -`bandwidth' & rdcontinuous <= `bandwidth'-1 & `variable' == `num', cluster(`cluster_dimension')
				local var_`cluster_dimension'_lockdown = _se[lockdown]^2		
				local var_`cluster_dimension'_day = _se[rdcontinuous]^2		
				local var_`cluster_dimension'_lockdown_rdcon= _se[lockdown_rdcon]^2	
			}
			
			* Dimesions for clustering:
			local cluster_vars_lockdown = 	 `var_PS_lockdown'  + `var_date_lockdown' - `var_ps_date_lockdown'
			local cluster_vars_day =     	 `var_PS_day' 		+ `var_date_day' 	  - `var_ps_date_day'
			local cluster_vars_lockdown_rdcon =`var_PS_lockdown_rdcon'  + `var_date_lockdown_rdcon' - `var_ps_date_lockdown_rdcon'

			* Replace _se[lockdown] with two-way clustered std error
		   tempvar esave		   
		   qui estsave, gen(`esave')
		   qui estsave, from(`esave')
		   tempname V 
		   matrix `V' = e(V)
		   matrix `V'[1,1] = `cluster_vars_lockdown'
		   matrix `V'[2,2] = `cluster_vars_day'
		   matrix `V'[3,3] = `cluster_vars_lockdown_rdcon'
		   ereturn repost V = `V'

			** Generate pre-lockdown mean;		
			sum  `crime_pre_mean' if rdcontinuous >= -`bandwidth' & rdcontinuous < 0 & year >= 2020 & `variable' == `num'		
			
			estadd scalar priordailymean = r(mean)
			estadd scalar shareofmean = _b[lockdown] / r(mean)	
			
			estadd scalar std_error_lockdown = (`var_PS_lockdown' + `var_date_lockdown' - `var_ps_date_lockdown')^0.5 
			estadd scalar significance = _b[lockdown] / e(std_error_lockdown)

			*Store the parameters
		   _eststo	`variable'`num'
			estimates store `variable'`num'
	
		}
	}
}
  end
    
* Run the program
twoway_clustered_se		 
 
#delimit;
estout, cells(b(/*star*/ fmt(3)) se(par fmt(3)) ) 
			keep (lockdown rdcontinuous lockdown_rdcon ) 
			stats(priordailymean shareofmean, fmt(%9.3f %9.3f) 
			labels("Average crime pre-lockdown" "Proportion"));

			
	#delimit;
	esttab using "tables and figures\Mechanisms.tex", /* b(%9.3f) se(%9.3f) nostar */
		keep(lockdown rdcontinuous lockdown_rdcon)	/*label*/ nonotes  
		subs("Date x Lockdown" "Date $\times$ Lockdown ") label
		mgroups( "Changes in Police Deployment"  "Changes in Criminal-Victim Matching"  , pattern(1 0 0 0 0 0 1 0 0 0) prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span})) 
		mtitle("\shortstack{Low Police\\Station}" "\shortstack{High Police\\Station}" "\shortstack{Low\\Judges}" "\shortstack{High\\Judges}"  "\shortstack{Low Police\\Officer}" "\shortstack{High Police\\Officer}" "\shortstack{Low Drop\\Mobility}" "\shortstack{High Drop\\Mobility}" "\shortstack{Low\\Compliance}" "\shortstack{High\\Compliance}" )
		replace
		$esttab_opts
		stats(N priordailymean shareofmean, fmt(%9.0fc %9.2f %9.2f) label("Observations" "Pre-lockdown Mean" "Share of Mean"));
		

 
 

 
*-------------------------------------------------------------------------------
*DYNAMIC ANALYSIS
*-------------------------------------------------------------------------------
use  "database_crime_covid.dta", clear	
 
* Define that the first week of the year starts on Sunday
	gen first = mdy(1, 1, year(date)) + 7 - dow(mdy(1, 1, year(date)))
		replace first = mdy(1, 1, year(date)) if dow(mdy(1, 1, year(date))) == 0
		format first %td
		
	gen week_no_year= ceil((date + 1 - first)/7)
		label var week_no_year "Week no (starting from Sunday to Saturday) within a Year"
		
	egen first_2 = min(first)
		format first_2 %td
		
	gen week_no_all = ceil((date + 1 - first_2)/7)
		label var week_no_all "Week no (starting from Sunday to Saturday). All Years."
	
br date first* week* dow if ps_code == 1

* Create variable for dynamic impact (event study)		
		gen week_t1 = week_no_year - 12
		label var week_t1 "Week no (Sunday to Saturday). treatment week=0"
		
		
* Keep from 5 Jan 2020 up to 1 August 2020
keep if week_t1>=-11 & week_t1<=18		
sort ps_code date week_no_all
global block_controls "share_urban share_male share_literacy share_SCST share_work"	 

collapse (sum) num_cases_adj num_cases_demeaned_adj property_crime_adj property_crime_demeaned_adj  personal_crime_adj personal_crime_demeaned_adj (first) date district real_district dist_code year migrants high_unemployment (mean) week_no_year week_t1 green orange red $block_controls (count) num_days =day , by(ps_code week_no_all)

label var week_no_year "Week"
encode district, gen(dist)
gen month = month(date)
  
* Dummies for each week
foreach num of numlist 11(-1)1 {
	gen week_n`num' = (week_t1 == - `num')
	label var week_n`num' "t=-`num'"
}

foreach num of numlist 0(1)18 {
	gen week_`num' = (week_t1 == `num')
	label var week_`num' "t=`num'"
}



*------------------------------------------------------------------------------*
* Figure 3
*------------------------------------------------------------------------------*
* 3(a) ALL CRIMES	
		* week_0 is the baseline. Trick to make week_0 ommitted
		clonevar copy_week_n1 = week_n1
		replace week_n1 = 0
		* Regress, adding the new variable
		areg  num_cases_demeaned_adj  week_n11 - week_n1  week_0  week_1 - week_18 copy_week_n1 $block_controls  if year == 2020 , cluster(dist) absorb(dist)
		* Coefplot
		coefplot, keep( week_*)   xline(12 16 18 22 26 28, lcolor(gray) lpattern(dash) lwidth(vthin)) vertical xlabel(,angle(45) labsize(small)) graphregion(fcolor(white) lcolor(white)) baselevels omitted 
		graph export "tables and figures\Eventstudy_demeaned.pdf" ,replace 			 
		
		
		
		
		
* 3(b) PROPERTY AND PERSONAL CRIMES	
	areg property_crime_demeaned_adj week_n11 - week_n1 week_0 week_1 - week_18 copy_week_n1 $block_controls green orange if year == 2020 , cluster(dist) absorb(dist)
		estimates store property
  	areg personal_crime_demeaned_adj week_n11 - week_n1 week_0 week_1 - week_18 copy_week_n1 $block_controls green orange if year == 2020 , cluster(dist) absorb(dist)
		estimates store personal
		estimates selected personal property

		coefplot (personal, label(Personal crimes) color(orange) ciopts(lcolor(orange))) (property, label(Property crimes) color(red) symbol(D) ciopts(lcolor(red))) , keep(week*)  xline(12 16 18 22 26 28, lcolor(gray) lpattern(dash) lwidth(vthin)) vertical xlabel(,angle(45)) graphregion(fcolor(white) lcolor(white))   legend(ring(0)  position(7)) baselevels omitted yline(0, lcolor(gs13) lpattern(shortdash))
	graph export "tables and figures\Eventstudy_demeaned_prop_pers.pdf" ,replace 		
		
	
	
	


*------------------------------------------------------------------------------*
* Figure 5 
*------------------------------------------------------------------------------*

capture	clonevar copy_week_n1 = week_n1
replace week_n1 = 0


* 5(a) Unemployment 			
quietly: areg property_crime_demeaned_adj week_n11 - week_n1 week_0 week_1 - week_18 copy_week_n1 green orange red  $block_controls if year == 2020 & high_unemployment == 1, cluster(dist) absorb(dist)
	estimates store high_U
quietly: areg property_crime_demeaned_adj week_n11 - week_n1 week_0 week_1 - week_18 copy_week_n1 green orange red  $block_controls if year == 2020 & high_unemployment == 0, cluster(dist) absorb(dist)
	estimates store low_U
	coefplot (high_U, label(High Unemployment) color(orange) ciopts(lcolor(orange))) (low_U, label(Low unemployment) color(blue) symbol(D) ciopts(lcolor(blue))) , keep(week_*)  xline(12 16 18 22 26 28, lcolor(gray) lpattern(dash) lwidth(vthin)) vertical xlabel(,angle(45)) graphregion(fcolor(white) lcolor(white)) legend(ring(0)  position(10)) baselevels omitted   
	graph export "tables and figures\property_crime_eventstudy_unemployment.pdf" ,replace 	
	

* 5(b) migration
quietly: areg property_crime_demeaned_adj week_n11 - week_n1 week_0 week_1 - week_18 copy_week_n1 green orange red  $block_controls  if year == 2020 & migrants == 1, cluster(dist) absorb(dist)
	estimates store high_migrants
quietly: areg property_crime_demeaned_adj week_n11 - week_n1 week_0 week_1 - week_18 copy_week_n1 green orange red  $block_controls if year == 2020 & migrants == 0, cluster(dist) absorb(dist)
	estimates store low_migrants
	coefplot (high_migrants, label(High Migrants) color(orange) ciopts(lcolor(orange))) (low_migrants, label(Low Migrants) color(blue) symbol(D) ciopts(lcolor(blue))) , keep(week_n2 /* week_n* week_0 */   week_*)   xline(12 16 18 22 26 28, lcolor(gray) lpattern(dash) lwidth(vthin)) vertical xlabel(,angle(45)) graphregion(fcolor(white) lcolor(white)) legend(ring(0)  position(10)) baselevels omitted
	graph export "tables and figures\property_crime_eventstudy_migrant.pdf" ,replace 
 
 